package com.mindcraft.shop.utils;

import com.mindcraft.base.handle.MindCraftLoginException;
import com.mindcraft.base.utils.CodeMsg;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.base.utils.JwtHelper;
import com.mindcraft.user.utils.MindCraftUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;


@Aspect
@Component
@Order(0)
@Slf4j
public class LoginCheckAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Around("@annotation(loginCheck)")
    public Object around(ProceedingJoinPoint joinPoint, LoginCheck loginCheck) throws Throwable {
        String token = MindCraftUtil.getRequest().getHeader(CommonConst.TOKEN);

        if (!StringUtils.hasText(token)) {
            throw new MindCraftLoginException(CodeMsg.NOT_LOGIN.getMsg());
        }

        String userId = JwtHelper.getUserId(token);



        if(redisTemplate.hasKey(CommonConst.USER_TOKEN_JWT+userId)){
            return joinPoint.proceed();
        }else{
            throw new MindCraftLoginException(CodeMsg.NOT_LOGIN.getMsg());
        }


    }
}
